package com.dxyxx.db;

import com.ta.utdid2.android.utils.StringUtils;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

/**
 * 一张表 对应 一个ContentProvider
 * 
 * @author chinesejie
 * 
 */
public class DataChangeProvider extends ContentProvider {
	// public static final String EXPRESS_LIST = "express_list";
	private DatabaseHelper mOpenHelper;
	private static String TABLENAME = "cart";
	private static final int PRODUCTS = 1;
	private static final int PRODUCT_ID = 2;
	private static final UriMatcher sURLMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	public static final Uri CONTENT_URI = Uri.parse("content://com.dxyxx/cart");

	static {
		sURLMatcher.addURI("com.dxyxx", TABLENAME, PRODUCTS);
		sURLMatcher.addURI("com.dxyxx", "cart/#", PRODUCT_ID);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return false;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "cart.db";
		private static final int DATABASE_VERSION = 1;

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			System.out.println("create a database");
			db.execSQL("create table cart(id INTEGER PRIMARY KEY AUTOINCREMENT,pid int,name varchar(20), amount int, description varchar(20),specification varchar(20), price varchar(10), thumb varchar(200))");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
			System.out.println("upgrade a database");
		}

	}

	@Override
	public int delete(Uri url, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();

		int count;
		switch (sURLMatcher.match(url)) {
		case PRODUCTS:
			count = db.delete(TABLENAME, where, whereArgs);
			break;
		case PRODUCT_ID:
			String segment = url.getPathSegments().get(1);
			if (TextUtils.isEmpty(where)) {
				where = "pid=" + segment;
			} else {
				where = "pid=" + segment + " AND (" + where + ")";
			}
			count = db.delete(TABLENAME, where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Cannot delete from URL: " + url);
		}

		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	@Override
	public String getType(Uri url) {
		int match = sURLMatcher.match(url);
		switch (match) {
		case PRODUCTS:

			return "vnd.android.cursor.dir/cart";
		case PRODUCT_ID:

			return "vnd.android.cursor.item/cart";
		default:
			throw new IllegalArgumentException("Unknown URL");
		}
	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		if (sURLMatcher.match(url) != PRODUCTS) {
			throw new IllegalArgumentException("Cannot insert into URL: " + url);
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		// 插入数据，咸查看数据中pid是否已经存在。
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(TABLENAME);
		Cursor cursor = qb.query(db, new String[] { "pid" }, "pid=?", new String[] { initialValues.getAsInteger("pid") + "" }, null, null, null);
		if (cursor.getCount() != 0) {
			db.delete(TABLENAME, "pid=?", new String[] { initialValues.getAsInteger("pid") + "" });
			db.insert(TABLENAME, null, initialValues);
		} else {
			db.insert(TABLENAME, null, initialValues);
		}
		cursor.close();
		getContext().getContentResolver().notifyChange(CONTENT_URI, null);// 通知数据库改变了
		return CONTENT_URI;
	}

	@Override
	public Cursor query(Uri url, String[] projection, String where, String[] whereArgs, String sortOrder) {
		// mOpenHelper.onUpgrade(mOpenHelper.getWritableDatabase(), 0, 0);
		// //删除数据
		// SQL:Select * From TABLE_NAME Limit 9 Offset 10; 跳过10行 查找9行
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		int match = sURLMatcher.match(url);
		switch (match) {
		case PRODUCTS:
			qb.setTables(TABLENAME);
			break;
		case PRODUCT_ID:
			qb.setTables(TABLENAME);
			qb.appendWhere("id=");
			qb.appendWhere(url.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cur = qb.query(db, projection, where, whereArgs, null, null, sortOrder);
		if (cur != null) {
			cur.setNotificationUri(getContext().getContentResolver(), url); // 告诉ContentResolver，数据准备好了
		}
		return cur;

	}

	// ** TODO
	@Override
	public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
		int count;
		long rowId = 0;
		int match = sURLMatcher.match(url);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		switch (match) {
		case PRODUCT_ID: {
			String segment = url.getPathSegments().get(1);
			rowId = Long.parseLong(segment);
			count = db.update(TABLENAME, values, "pid=" + rowId, null);
			break;
		}
		default: {
			throw new UnsupportedOperationException("Cannot update URL: " + url);
		}
		}
		//getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

}
